package com.example.book.sys.user.service;

import com.example.book.base.BaseService;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.sys.SysMenu;
import com.example.book.sys.menu.service.SysMenuService;
import com.example.book.domain.sys.SysRoleMenu;
import com.example.book.sys.role.service.SysRoleMenuService;
import com.example.book.sys.user.dao.SysUserDao;
import com.example.book.domain.sys.SysDeptPost;
import com.example.book.domain.sys.SysUser;
import com.example.book.domain.sys.SysUserRole;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author haocj
 * 用户service
 */
@Service
public class SysUserService extends BaseService<SysUser, SysUserDao> {

    @Resource
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysDeptPostService sysDeptPostService;
    @Autowired
    private RedisService redisService;

    public SysUser findByNameOrPass(SysUser sysUser) {
        return sysUserDao.findByNameOrPass(sysUser);
    }


    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void save(SysUser sysUser, String[] ids) {

        sysUser.setPassword(new Sha256Hash(sysUser.getPassword()).toHex());

        super.save(sysUser);

        // 修改信息时
        if (StringUtils.isNotBlank(sysUser.getId())) {
            //删除角色信息
            sysUserRoleService.deleteById(sysUser.getId());
            // 删除部门信息
            sysDeptPostService.delete(sysUser.getId());
        }

        // 新增角色信息
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole sysUserRole = null;
        for (String id : ids) {
            sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(id);
            list.add(sysUserRole);
        }
        sysUserRoleService.save(list);

        // 新增 部门信息
        SysDeptPost sysDeptPost = new SysDeptPost();
        sysDeptPost.setUserId(sysUser.getId());
        sysDeptPost.setDeptId(sysUser.getDeptId());
        sysDeptPost.setPostId(sysUser.getPostId());
        sysDeptPostService.save(sysDeptPost);
    }


    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public Integer delete(String[] ids) {
        sysUserDao.delete(ids);
        return sysUserRoleService.delete(ids);
    }


    /**
     * 查询用户角色权限标识
     *
     * @param id
     * @return
     */
    public Set<String> queryPermissions(String id) {
        List<String> permsList = null;
        // 查询角色id集合
        List<SysUserRole> roleList = null;
        //系统管理员，拥有最高权限，不缓存角色信息
        if (Constants.SUPER_ADMIN.equals(id)) {
            List<SysMenu> menuList = sysMenuService.findList(new SysMenu());
            permsList = new ArrayList<>();
            for (SysMenu menu : menuList) {
                permsList.add(menu.getPermission());
            }
        } else {
            roleList = sysUserRoleService.findList(id);
            if (roleList.size() > 0) {
                redisService.set(Constants.USER_ROLE_CACHE+id, roleList);
                List<String> roleIds = new ArrayList<String>();
                for (SysUserRole userRole : roleList) {
                    roleIds.add(userRole.getRoleId());
                }
                if (roleIds.size() > 0) {
                    // 查询角色下所有菜单id结合
                    List<SysRoleMenu> list = roleMenuService.findRoleMenuList(roleIds);
                    permsList = new ArrayList<String>();
                    for (SysRoleMenu roleMenu : list) {
                        SysMenu menu = sysMenuService.get(roleMenu.getMenuId());
                        permsList.add(menu.getPermission());
                    }
                }
            }
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        if (permsList != null && permsList.size() != 0) {
            for (String perms : permsList) {
                if (StringUtils.isBlank(perms)) {
                    continue;
                }
                // 可以多个权限以逗号分割
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }
        return permsSet;
    }

}
